﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using System.Web;
using System.Web.Mvc;

namespace SCS.Core.Controllers
{
    public class AdvertiesMasterController:BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("ListAdverties");
        }

        #region "Adverties"
        public ActionResult AddAdverties()
        {
            var adverties = new Models.Collection.AdvertiesCollection();
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());


            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);
          

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailAdverties", adverties);      ///Return to view detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAdd(FormCollection collection)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var adverties = new Models.Collection.AdvertiesCollection();
            TryUpdateModel(adverties);
            int advId = 0;
            try
            {

                //Create Adverties
                SCSService.Adverty adv = new Adverty();
                adv.AdvertiesName = adverties.AdvertiesName;
                adv.AdvertiesUrl = adverties.AdvertiesUrl;
                adv.AdvertiesTarget = adverties.AdvertiesTarget;
                if (adv.AdvertiesPromotion != null)
                {
                    adv.AdvertiesPromotion = (int)adverties.AdvertiesPromotion;
                }
                else
                {
                    adv.AdvertiesPromotion = 0;
                }
                if (adv.AdvertiesType != null)
                {
                    adv.AdvertiesType = (int)adverties.AdvertiesType;
                }
                else
                {
                    adv.AdvertiesType = 0;
                }
                if (adv.AdvertiesView != null)
                {
                    adv.AdvertiesView = (int)adverties.AdvertiesView;
                }
                else
                {
                    adv.AdvertiesView = 0;
                }
                adv.AdvertiesIP = adverties.AdvertiesIP;

                adv.AdvertiesPageID = adverties.AdvertiesPageID;
                adv.AdvertiesActive = adverties.AdvertiesActive;
                adv.LanguagesID = adverties.LanguagesID;
                adv.SiteGuid = DefaultSiteGuidGetter();

                if (adverties.Sort == null)
                {
                    adv.Sort = Models.AdvertiesMasterModel.GetCountAdverties(LanguageID, GetSiteGuid()) + 1 ;
                }
                else
                {
                    adv.Sort = (int)adverties.Sort;    
                }
                               

                advId = Models.AdvertiesMasterModel.CreateAdverties(adv);

                ViewData["Result"] = "Create Adverties Success!";

            }
            catch
            {
                return View("DetailAdverties", new Models.Collection.AdvertiesCollection());     //return to detail
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/AdvertiesMaster/EditAdverties/" + advId);
        }

        public ActionResult EditAdverties(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();

            Adverty adv = Models.AdvertiesMasterModel.GetAdverties(id);
           
            var adverties = new Models.Collection.AdvertiesCollection();
            adverties.AdvertiesID = adv.AdvertiesID;
            adverties.AdvertiesName = adv.AdvertiesName;
            adverties.AdvertiesUrl = adv.AdvertiesUrl;
            adverties.AdvertiesTarget = adv.AdvertiesTarget;
            adverties.AdvertiesPromotion = adv.AdvertiesPromotion;
            adverties.AdvertiesType = adv.AdvertiesType;
            adverties.AdvertiesView = adv.AdvertiesView;
            adverties.AdvertiesIP = adv.AdvertiesIP;
            adverties.AdvertiesPageID = adv.AdvertiesPageID;
            adverties.AdvertiesActive = (bool)adv.AdvertiesActive;

            if (adv.LanguagesID != null)
            {
                adverties.LanguagesID = adv.LanguagesID;
            }        
            

            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", adv.LanguagesID != null ? adv.LanguagesID : 0);
           
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailAdverties", adverties);      ///return to detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEdit(FormCollection collection)
        {
            var adverties = new Models.Collection.AdvertiesCollection();
            TryUpdateModel(adverties);
            int siteGuid = GetSiteGuid();
            
            try
            {
                //Update Adverties
                SCSService.Adverty adv = Models.AdvertiesMasterModel.GetAdverties(adverties.AdvertiesID);
                adv.AdvertiesName = adverties.AdvertiesName;
                adv.AdvertiesUrl = adverties.AdvertiesUrl;
                adv.AdvertiesTarget = adverties.AdvertiesTarget;
                adv.AdvertiesPromotion = adverties.AdvertiesPromotion;
                adv.AdvertiesType = adverties.AdvertiesType;
                adv.AdvertiesView = adverties.AdvertiesView;
                adv.AdvertiesIP = adverties.AdvertiesIP;
                if (adv.AdvertiesPageID != null)
                {
                    adv.AdvertiesPageID = adverties.AdvertiesPageID;
                }
                adv.AdvertiesActive = adverties.AdvertiesActive;
                adv.LanguagesID = adverties.LanguagesID;
                adv.SiteGuid = DefaultSiteGuidGetter();
                if (adverties.Sort != null)
                {
                    adv.Sort = (int)adverties.Sort;
                }

                
                //Call Update method
                Models.AdvertiesMasterModel.UpdateAdverties(adv);

                ViewData["Result"] = "Update Adverties Success!";

            }
            catch
            {
                return View("", new Models.Collection.AdvertiesCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/AdvertiesMaster/EditAdverties/" + adverties.AdvertiesID);
        }
        

        public ActionResult UdpateSortIndex(int? id, int? proid)
        {
            Models.AdvertiesMasterModel.UpdateSortAdverties(id, proid);
            string result = "" + proid;
            return Json(result);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.AdvertiesViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.AdvertiesViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        public StringBuilder GetListAdvertiesBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListAdvertiesBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public static SelectList SetOrder(int langauesID, int siteGuid)
        {

            int count = Models.AdvertiesMasterModel.GetCountAdverties(langauesID, siteGuid);
            var tp = new List<string> { };
            for (int i = 1; i < (count + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp);
        }


        public StringBuilder ListAdvertiesBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Adverty> listcate = Models.AdvertiesMasterModel.GetListAdverties(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Adverties");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/AdvertiesMaster/EditAdverties/" + item.AdvertiesID + "'>" + item.AdvertiesName + "</a>");
                List<SCSService.Adverty> listChild = Models.AdvertiesMasterModel.GetListAdverties(item.AdvertiesID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListAdvertiesBuilder(ref sb, item.AdvertiesID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListAdverties(string SAdvertiesName, string SAdvertiesUrl, string SAdvertiesTarget, int? SAdvertiesPromotion, int? SAdvertiesType, int? SAdvertiesView, string SAdvertiesIP, string SAdvertiesPageID, bool? SAdvertiesActive, int? SSort)
        {
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "Sort";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListAdverties"] = GetListAdvertiesBuilder(null, LanguageID, siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, siteGuid);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListAdverties(SAdvertiesName, SAdvertiesUrl, SAdvertiesTarget, SAdvertiesPromotion, SAdvertiesType, SAdvertiesView, SAdvertiesIP, SAdvertiesPageID, SAdvertiesActive,currentPage, pageSize, sortField, sortDirection, null, siteGuid, SSort);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListAdverties(string SAdvertiesName, string SAdvertiesUrl, string SAdvertiesTarget, int? SAdvertiesPromotion,int? SAdvertiesType, int? SAdvertiesView, string SAdvertiesIP, string SAdvertiesPageID, bool? SAdvertiesActive, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid, int? SSort)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListAdverties"] =  GetListAdvertiesBuilder(null, LanguageID, (int)siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, (int)siteGuid);

            var query = GetListAdvertiesDropBasic(SAdvertiesName, SAdvertiesUrl, SAdvertiesTarget, SAdvertiesPromotion, SAdvertiesType, SAdvertiesView, SAdvertiesIP, SAdvertiesPageID, SAdvertiesActive, LanguageID, (int)siteGuid, SSort).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Adverty), "Adverties");
                var sortExpression = Expression.Lambda<Func<Adverty, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Adverty>();

            // Set up our ViewModel
            var viewModel = new AdvertiesViewModels
            {               
                AdvertiesList=result,
                sAdvertiesName=SAdvertiesName,
                sAdvertiesUrl=SAdvertiesUrl,
                sAdvertiesActive=SAdvertiesActive,
                sSort=SSort                
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public List<Adverty> GetListAdvertiesDropBasic(string AdvertiesName, string AdvertiesUrl, string AdvertiesTarget, int? AdvertiesPromotion, int? AdvertiesType, int? AdvertiesView, string AdvertiesIP, string AdvertiesPageID, bool? AdvertiesActive, int LanguagesID, int siteGuid, int? Sort)
        {
            List<Adverty> sb = new List<Adverty>();
            return ListAdvertitesDropBasic(AdvertiesName, AdvertiesUrl, AdvertiesTarget, AdvertiesPromotion, AdvertiesType, AdvertiesView, AdvertiesIP, AdvertiesPageID, AdvertiesActive, ref sb, true, LanguagesID, siteGuid, Sort);
        }

        public List<Adverty> ListAdvertitesDropBasic(string AdvertiesName, string AdvertiesUrl, string AdvertiesTarget, int? AdvertiesPromotion,int? AdvertiesType, int? AdvertiesView, string AdvertiesIP,string AdvertiesPageID,bool? AdvertiesActive, ref List<Adverty> sb,bool root, int LanguagesID, int siteGuid, int? Sort)
        {
            List<SCSService.Adverty> listcate = Models.AdvertiesMasterModel.GetListAdvertiesSearch(LanguagesID, siteGuid,AdvertiesName,AdvertiesUrl,AdvertiesTarget,AdvertiesPromotion, AdvertiesType, AdvertiesView, AdvertiesIP, AdvertiesPageID, AdvertiesActive,Sort);

            foreach (var item in listcate)
            {
                if (!root)
                {
                    foreach (var itemStr in sb)
                    {
                        
                            if (itemStr.AdvertiesName.Contains(">>"))
                            {
                                int laststr = itemStr.AdvertiesName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.AdvertiesName.Substring(0, laststr);
                                item.AdvertiesName = addStr + item.AdvertiesName;
                            }                       
                    }

                }             
                
                sb.Add(item);
                List<SCSService.Adverty> listChild = Models.AdvertiesMasterModel.GetListAdvertiesSearch(LanguagesID, siteGuid, AdvertiesName,AdvertiesUrl,AdvertiesTarget,AdvertiesPromotion,AdvertiesType, AdvertiesView,AdvertiesIP, AdvertiesPageID,AdvertiesActive,Sort);
                if (listChild.Count() > 0)
                {                    
                    ListAdvertitesDropBasic(AdvertiesName,AdvertiesUrl,AdvertiesTarget,AdvertiesPromotion,AdvertiesType,AdvertiesView, AdvertiesIP,AdvertiesPageID,AdvertiesActive, ref sb,false,LanguagesID,siteGuid,Sort);
                }

            }

            return sb;
        }


        public static bool CheckDeleteAdverties(int id)
        {
            int count = Models.ArticaleMasterModel.GetCountStaticArticleInArticleCategory(id);
            return count > 0 ? false : true;
        }

        public ActionResult DeleteAdverties(int id, string returnUrl)
        {
            if (CheckDeleteAdverties(id))
            {
                Models.AdvertiesMasterModel.DeleteAdverties(id);
                ViewData["Result"] = "Delete success!";
            }
           
            return Redirect(returnUrl);
        }
        #endregion

       
    }
}
